package com.cuiweiyou.adbctoller.util;

import com.cuiweiyou.adbctoller.Constant;
import com.cuiweiyou.adbctoller.bean.DeviceModel;
import com.cuiweiyou.adbctoller.bean.WechatNumberModel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

/**
 * www.gaohaiyan.com
 */
public class FileUtil {

    public synchronized static void saveLog(String log) {
        saveLogs(new ArrayList<String>() {
            {
                add(DateUtil.getNowYYMMDDHHmmss() + "_" + log);
            }
        });
    }

    public synchronized static void saveLogs(List<String> log) {
        if (null == log || log.size() < 1) {
            return;
        }

        File file;
        if (null != Constant.lastLogFilePath) {
            file = new File(Constant.lastLogFilePath);
            long length = file.length(); // byte
            System.out.println("========---------========--------" + length);
            if (length > 1024 * 1024 * 10) { // 10MB
                Constant.lastLogFilePath = createLogFile();
                file = new File(Constant.lastLogFilePath);
            }

            appendLine2File(file.getAbsolutePath(), log);
        }
    }

    private static void appendLine2File(String filePath, List<String> strList) {
        if (null == strList || strList.size() < 1) {
            return;
        }

        File file = new File(filePath);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        BufferedWriter bufferedWriter = null;
        try {
            bufferedWriter = new BufferedWriter(new FileWriter(file.getAbsoluteFile(), true)); // true 可以追加新内容
            for (int i = 0; i < strList.size(); i++) {
                String string = strList.get(i);

                System.out.println("LOG--" + string);

                bufferedWriter.write(string + System.getProperty("line.separator"));
                bufferedWriter.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bufferedWriter) {
                    bufferedWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String readLastLineFromFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return "";
        }

        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "r");
            long len = raf.length();
            String lastLine = "";
            if (len != 0L) {
                long pos = len - 1;
                while (pos > 0) {
                    pos--;
                    raf.seek(pos);
                    byte b = raf.readByte();
                    if (b == '\n') {
                        lastLine = raf.readLine().trim();
                        if (lastLine.length() > 0) {
                            break;
                        }
                    }
                }
            }
            raf.close();
            return lastLine;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != raf) {
                try {
                    raf.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    public static String createLogFolder() {
        String path = Constant.sourceWorkSpace + "log/";
        File file = new File(path);
        if (file.exists()) {
            if (!file.isDirectory()) {
                file.mkdirs();
            }
        } else {
            file.mkdirs();
        }

        return path;
    }

    public static void createDiffDeviceFile(List<DeviceModel> list) {
        if (null == list || list.size() < 1) {
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            String sn = list.get(i).getSn().toLowerCase();
            String path = Constant.sourceWorkSpace + "device_" + sn + ".txt";
            createFile(path);
        }
    }

    public static void createDiffFriendFile(List<DeviceModel> list) {
        if (null == list || list.size() < 1) {
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            String sn = list.get(i).getSn().toLowerCase();
            String path = Constant.sourceWorkSpace + "friend_" + sn + ".txt";
            createFile(path);
        }
    }

    public static void createDiffGimmickFile(List<DeviceModel> list) {
        if (null == list || list.size() < 1) {
            return;
        }

        for (int i = 0; i < list.size(); i++) {
            String sn = list.get(i).getSn().toLowerCase();
            String path = Constant.sourceWorkSpace + "gimmick_comm_" + sn + ".txt";
            createFile(path);
        }

        for (int i = 0; i < list.size(); i++) {
            String sn = list.get(i).getSn().toLowerCase();
            String path = Constant.sourceWorkSpace + "gimmick_hello_" + sn + ".txt";
            createFile(path);
        }
    }

    public static String createLogFile() {
        String logFolder = createLogFolder();// 创建日志文件夹前
        String path = logFolder + "log_" + DateUtil.getNowYYMMDDHHmmss() + ".log";
        return createFile(path);
    }

    private synchronized static String createFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            try {
                file.createNewFile();
                FileUtil.saveLogs(LineSeparatorUtil.transformStrigToListLog("创建文件", path));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return path;
    }

    public static boolean isExistsFileOrFloder(String path) {
        boolean result = false;
        if (null != path) {
            if (path.length() > 0) {
                File file = new File(path);
                if (file.isDirectory()) {
                    if (file.exists()) {
                        result = true;
                    }
                } else {
                    if (file.exists()) {
                        result = true;
                    }
                }
            }
        }

        return result;
    }

    public static List<WechatNumberModel> getWechatNumberList(String filePath) {
        List<WechatNumberModel> result = new ArrayList<>();
        FileReader fr = null;
        BufferedReader bf = null;
        try {
            fr = new FileReader(filePath);
            bf = new BufferedReader(fr);
            String line;
            while ((line = bf.readLine()) != null) {
                line = line.replaceAll(" ", "");
                if (!"".equals(line)) {
                    WechatNumberModel f = new WechatNumberModel(line);
                    result.add(f);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fr) {
                try {
                    fr.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != bf) {
                try {
                    bf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
